/**
 * @file ai_system_controller.cpp
 * @brief Implementation of AI system controller
 */

#include "ai_system_controller.h"
#include <wx/file.h>
#include <wx/textfile.h>

AISystemController::AISystemController()
    : m_router(AIMessageRouter::GetInstance())
    , m_currentMode(MODE_INTERACTIVE)
    , m_isRunning(false)
{
}

AISystemController::~AISystemController()
{
    StopSystem();
}

bool AISystemController::StartSystem(SystemMode mode)
{
    if (m_isRunning) {
        wxPrintf("⚠️  System is already running\n");
        return true;
    }
    
    if (!m_router.Initialize()) {
        wxPrintf("❌ Failed to initialize message router\n");
        return false;
    }
    
    m_currentMode = mode;
    m_isRunning = true;
    
    wxPrintf("🚀 AI System Started - Mode: %s\n", 
        mode == MODE_INTERACTIVE ? "Interactive" :
        mode == MODE_BATCH ? "Batch" :
        mode == MODE_SERVICE ? "Service" : "Debug");
    
    return true;
}

void AISystemController::StopSystem()
{
    if (m_isRunning) {
        m_isRunning = false;
        wxPrintf("🛑 AI System Stopped\n");
    }
}

int AISystemController::ProcessCommandLine(int argc, char* argv[])
{
    if (argc < 2) {
        wxPrintf("Usage: cbp2make_ai.exe <mode> [options]\n");
        wxPrintf("Modes:\n");
        wxPrintf("  --ai-interactive    Interactive AI terminal\n");
        wxPrintf("  --ai-batch <file>   Execute batch commands from file\n");
        wxPrintf("  --ai-service        Run as AI service\n");
        wxPrintf("  --ai-debug          Debug mode\n");
        wxPrintf("  --ai-status         Show system status\n");
        return 1;
    }
    
    wxString mode = argv[1];
    
    if (mode == "--ai-interactive") {
        StartSystem(MODE_INTERACTIVE);
        RunInteractiveMode();
        return 0;
    } else if (mode == "--ai-batch") {
        if (argc < 3) {
            wxPrintf("Error: Batch mode requires script file\n");
            return 1;
        }
        return ExecuteScriptFile(argv[2]);
    } else if (mode == "--ai-service") {
        StartSystem(MODE_SERVICE);
        RunServiceMode();
        return 0;
    } else if (mode == "--ai-debug") {
        StartSystem(MODE_DEBUG);
        RunDebugMode();
        return 0;
    } else if (mode == "--ai-status") {
        wxPrintf("%s\n", GetStatusReport());
        return 0;
    } else {
        wxPrintf("Error: Unknown mode '%s'\n", mode);
        return 1;
    }
}

void AISystemController::RunInteractiveSession()
{
    StartSystem(MODE_INTERACTIVE);
    RunInteractiveMode();
}

int AISystemController::ExecuteScriptFile(const wxString& scriptPath)
{
    if (!wxFileExists(scriptPath)) {
        wxPrintf("❌ Script file not found: %s\n", scriptPath);
        return 1;
    }
    
    wxTextFile file;
    if (!file.Open(scriptPath)) {
        wxPrintf("❌ Cannot open script file: %s\n", scriptPath);
        return 1;
    }
    
    std::vector<wxString> commands;
    for (size_t i = 0; i < file.GetLineCount(); i++) {
        wxString line = file[i].Trim();
        if (!line.IsEmpty() && !line.StartsWith("#")) {
            commands.push_back(line);
        }
    }
    
    file.Close();
    
    StartSystem(MODE_BATCH);
    RunBatchMode(commands);
    
    return 0;
}

wxString AISystemController::GetStatusReport() const
{
    wxString report = "🤖 AI System Status Report\n";
    report += "=======================\n";
    report += wxString::Format("Running: %s\n", m_isRunning ? "Yes" : "No");
    report += wxString::Format("Mode: %s\n", 
        m_currentMode == MODE_INTERACTIVE ? "Interactive" :
        m_currentMode == MODE_BATCH ? "Batch" :
        m_currentMode == MODE_SERVICE ? "Service" : "Debug");
    report += m_router.GetSystemStatus();
    return report;
}

void AISystemController::RunInteractiveMode()
{
    HumanAITerminal terminal;
    terminal.StartInteractiveDialog();
}

void AISystemController::RunBatchMode(const std::vector<wxString>& commands)
{
    HumanAITerminal terminal;
    terminal.ExecuteBatchCommands(commands);
}

void AISystemController::RunServiceMode()
{
    wxPrintf("🔧 AI Service Mode - Listening for requests...\n");
    
    // 服务模式可以监听网络请求或文件变化
    // 这里简化为等待一段时间
    for (int i = 0; i < 10 && m_isRunning; i++) {
        wxPrintf("Service running... %d/10\n", i + 1);
        wxMilliSleep(1000);
    }
    
    wxPrintf("Service mode completed.\n");
}

void AISystemController::RunDebugMode()
{
    wxPrintf("🐛 AI Debug Mode\n");
    
    // 测试消息路由
    AIMessage testMsg;
    testMsg.msgType = MessageType::COMMAND_TO_AI;
    testMsg.source = TerminalType::HUMAN_TO_AI;
    testMsg.destination = TerminalType::AI_TO_COMPUTER;
    testMsg.content = "debug test command";
    testMsg.messageId = "debug_test_1";
    
    m_router.SendMessage(testMsg);
    
    wxPrintf("Debug test completed.\n");
}

AIMessage AISystemController::ParseCommandLine(const wxString& commandLine)
{
    AIMessage message;
    message.msgType = MessageType::COMMAND_TO_AI;
    message.source = TerminalType::HUMAN_TO_AI;
    message.destination = TerminalType::AI_TO_COMPUTER;
    message.content = commandLine;
    message.messageId = wxString::Format("cli_%lld", wxGetLocalTime());
    
    return message;
}
